import { element } from 'protractor';
import { Component, Injector, ViewChild } from '@angular/core';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { MessageService } from '@abp/message/message.service';
import { Table } from 'primeng/components/table/table';
import { Paginator } from 'primeng/components/paginator/paginator';
import { OrganizationUnitDto, WorkLabelOutPut, BackInput, JobWorkerOut, MakeReportInput, InspectionSeverityDescOutDto, InspectionStartServiceProxy, InspectionFileUploadDto, DefendJobWorkerInput, InspectionFileCommonServiceServiceProxy, InspectionStandardDescDto, ProductionAssignmentServiceProxy, OperationHistoryServiceProxy, OperationLogDto, ProductionReportServiceProxy, CodeFormatDescServiceProxy, CodeFormatDto } from '@shared/service-proxies/service-proxies';
import { finalize, filter } from 'rxjs/operators';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as moment from 'moment';
import { AppSessionService } from '@shared/common/session/app-session.service';
@Component({
    selector: 'app-work-repor',
    templateUrl: './work-repor.component.html',
    styleUrls: ['./work-repor.component.less']
})
export class WorkReporComponent extends AppComponentBase {
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;
    logList: OperationLogDto[];
    getOrganizationUnitUsersByIdList: any;
    getOrganizationUnitList: OrganizationUnitDto[];
    productingStatus: WorkLabelOutPut[];
    uploadedFiles: any = [];
    cancelVisible: boolean = false;
    cancelVal: string;
    taskInfo = undefined
    formatDropList: CodeFormatDto[] = [];
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _productionAssignmentServiceProxy: ProductionAssignmentServiceProxy,
        private _productionReportServiceProxy: ProductionReportServiceProxy,
        private _inspectionStartServiceProxy: InspectionStartServiceProxy,
        private _operationHistoryServiceProxy: OperationHistoryServiceProxy,
        private _inspectionFileCommonServiceServiceProxy: InspectionFileCommonServiceServiceProxy,
        private _user: AppSessionService,
        private _codeFormatDescServiceProxy: CodeFormatDescServiceProxy,
    ) {
        super(injector);
    }
    addInfoUi: any = {
        inspectionTypeDescId: undefined,//一级异常id
        inspectionItemInfoId: undefined,//二级异常id
        inspectionSeverityDescId: undefined,//异常等级id
        handlerId: undefined,//处理人id
        inspectionDetails: "",//异常描述
        codeFormatId: undefined,//编码规则id
        inspectionFileUploadDto: [],
        taskCode: undefined
    };//新增集合
    queryInfo = {
        jobNumber: "",
        techniqueName: "",
        techniqueNumber: "",
        processesName: "",
        workStepName: "",
        startTime: null,
        endTime: null,
        time: "",
        assemblyTime: "",
        organizationUnitDesc: "",
        userName: "",
        productingStatus: undefined,
        assemblyStartTime: null,
        assemblyEndTime: null,
        inspectionTypeDescId: "",
        organizationUnitId: ""
    };//查询条件
    addVisible: boolean = false;//弹窗 参数
    llVisible: boolean = false;//履历 参数
    addInfo = new InspectionStandardDescDto();//新增集合
    userList: any[];//调度员下拉
    savingAddDia: boolean = false;//禁止频繁保存操作
    selectRow: any = [];
    typeDescList: any[];//一级异常下拉
    itemInfoList: any[];//二级异常下拉
    severityDescList: InspectionSeverityDescOutDto[];//等级下拉
    reportingVisible: boolean = false;//报工任务弹窗
    crewVisible: boolean = false;
    crewArr: any;
    crewListArr: any = [];
    cancelInfo: any
    selectTablelist: any[] = []
    saveFlag = true;
    flag = true;
    taskTitle = undefined;
    getTableCheckBox(car) {
        this.flag = false;
        setTimeout(() => {
            this.selectTablelist.push(car);
            this.flag = true;
        }, 5);
    }
    ngOnInit() {
        this.getItemInfoList()
        this.getProductingStatusDescEv()
        this.gettypeDescList()
        this.getSeverityDescList()
        this.getuserList()
        this.getFormatDropList()
        this.getOrganizationUnit()
    }
    // 撤销
    cancelEv() {
        let backInfo = new BackInput()
        backInfo.id = this.cancelInfo.id
        backInfo.backReason = this.cancelVal
        this._productionReportServiceProxy.backTaskReport(
            backInfo
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.cancelVisible = false
                this.getDescList()
            });
    }
    //  班组维护 保存
    defendJobWorkerEv(): void {
        if (this.selectRow.length === 0) {
            this._messageService.warn("请选择要维护的列表")
            return
        }
        let inputInfo = new DefendJobWorkerInput()
        inputInfo.userId = ""
        inputInfo.userName = ""
        inputInfo.organizationUnitId = ""
        inputInfo.organizationUnitDesc = ""
        let userIdSelect = this.getOrganizationUnitUsersByIdList.filter(item => {
            return item.val.length != 0
        })
        this.crewListArr.forEach(element => {
            inputInfo.organizationUnitId += `${element.id},`
            inputInfo.organizationUnitDesc += `${element.displayName},`
        });
        userIdSelect.forEach(element => {
            inputInfo.userId += `${element.id},`
            inputInfo.userName += `${element.name},`
        });
        inputInfo.userId = inputInfo.userId.substring(0, inputInfo.userId.length - 1)
        inputInfo.organizationUnitId = inputInfo.organizationUnitId.substring(0, inputInfo.organizationUnitId.length - 1)
        inputInfo.organizationUnitDesc = inputInfo.organizationUnitDesc.substring(0, inputInfo.organizationUnitDesc.length - 1)
        inputInfo.userName = inputInfo.userName.substring(0, inputInfo.userName.length - 1)
        inputInfo.idList = []
        this.selectRow.forEach(element => {
            inputInfo.idList.push(element.id)
        });
        if (this.saveFlag) {
            this.saveFlag = false;
            this._productionReportServiceProxy.defendJobWorker(
                inputInfo
            )
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this.crewVisible = false
                        this._messageService.success("成功")
                        this.getDescList()
                    } else {
                        this._messageService.error(result.message)
                    }
                });
        }
    }
    // 工时提报 0 提报  1 结束提报 2  重新启用提报
    performanceHourEv(type) {
        if (this.selectTablelist.length == 0) {
            this._messageService.error("请先选择报工列表")
            return
        }
        let hourInfo = new MakeReportInput()
        hourInfo.operation = type
        hourInfo.taskId = this.taskInfo.id
        hourInfo.jobWorkers = []
        let jo: JobWorkerOut[] = []
        let cdee = JSON.parse(JSON.stringify(this.taskInfo.jobWorkers))
        cdee.forEach(element => {
            let etie = new JobWorkerOut()
            etie.backReason = element.backReason
            etie.id = element.id
            etie.isCheck = true
            etie.performanceHour = element.performanceHour
            etie.remark = element.remark
            etie.reportHour = element.reportHour
            etie.sort = element.sort
            etie.taskId = element.taskId
            etie.backReason = element.backReason
            etie.userId = element.userName ? element.userName.id : element.userId
            etie.userName = element.userName ? element.userName.userName : element.userName
            etie.organizationUnitId = element.organizationUnitDesc ? element.organizationUnitDesc.id : element.organizationUnitId
            etie.organizationUnitDesc = element.organizationUnitDesc ? element.organizationUnitDesc.displayName : element.organizationUnitDesc
            jo.push(etie)
        });
        hourInfo.jobWorkers = jo
        if (this.saveFlag) {
            this.saveFlag = false;
            this._productionReportServiceProxy.makeRepot(
                hourInfo
            )
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this.reportingVisible = false
                        this._messageService.success("提报成功")
                        this.getDescList()
                    } else {
                        this._messageService.error(result.message)
                    }

                });
        }
    }
    onUpload(event) {
        for (let file of event.files) {
            this.uploadedFiles.push(file);
        }
    }
    //删除报工
    removeEv(car) {
        let list = this.taskInfo.jobWorkers.filter(item => {
            return item.id != car.id
        })
        this.taskInfo.jobWorkers = list
    }
    //添加报工人
    addEv() {
        let info: any = {
            getOrganizationUnitList: undefined, getOrganizationUnitUsersByIdList: undefined, id: undefined, taskId: undefined
            , sort: undefined, organizationUnitId: undefined, organizationUnitDesc: undefined, userId: undefined, userName: undefined,
            performanceHour: undefined, reportHour: undefined, reportTime: undefined, remark: undefined, backReason: undefined, isCheck: undefined
        };
        info.getOrganizationUnitList = this.getOrganizationUnitList
        info.getOrganizationUnitUsersByIdList = this.getOrganizationUnitUsersByIdList
        info.id = undefined;
        info.taskId = undefined
        info.sort = undefined
        info.organizationUnitId = undefined
        info.organizationUnitDesc = undefined
        info.userId = undefined
        info.userName = undefined
        info.performanceHour = undefined
        info.reportHour = undefined
        info.reportTime = undefined
        info.remark = undefined
        info.backReason = undefined
        info.isCheck = undefined
        this.taskInfo.jobWorkers.push(
            info
        )
    }
    // 生产报工详情
    getTaskByIdEv(id): void {
        this._productionReportServiceProxy.getTaskById(
            id
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.taskTitle = '生产报工'
                this.reportingVisible = true
                this.taskInfo = result
                this.taskInfo.jobWorkers.forEach(item => {
                    let em = {
                        id: item.organizationUnitId
                    }
                    this.unitChangeonlyEv(em, item)

                    item.getOrganizationUnitList = this.getOrganizationUnitList
                    item.organizationUnitDesc = this.getOrganizationUnitList.filter((ele, index) => {
                        return ele.id === item.organizationUnitId
                    })[0]
                })
            });
    }
    watchTaskByIdEv(id) {
        this._productionReportServiceProxy.getTaskById(
            id
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.taskTitle = '生产报工查看'
                this.reportingVisible = true
                this.taskInfo = result
                this.taskInfo.jobWorkers.forEach(item => {
                    let em = {
                        id: item.organizationUnitId
                    }
                    this.unitChangeonlyEv(em, item)

                    item.getOrganizationUnitList = this.getOrganizationUnitList
                    item.organizationUnitDesc = this.getOrganizationUnitList.filter((ele, index) => {
                        return ele.id === item.organizationUnitId
                    })[0]
                })
            });
    }
    //一级异常 下拉列表
    gettypeDescList(): void {
        this._inspectionStartServiceProxy.getInspectionTypeDescList(
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.typeDescList = result
            });
    }
    //二级异常 下拉列表
    getItemInfoList(): void {
        this._inspectionStartServiceProxy.getInspectionItemInfoList(
            this.addInfoUi.inspectionTypeDescId ? this.addInfoUi.inspectionTypeDescId.id : undefined,
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.itemInfoList = result
            });
    }
    //异常等级 下拉列表
    getSeverityDescList(): void {
        this._inspectionStartServiceProxy.getInspectionSeverityDescList(
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.severityDescList = result
            });
    }
    //提报人/处理人 下拉列表
    getuserList(): void {
        this._inspectionStartServiceProxy.getUserList(
            this.addInfoUi.inspectionItemInfoId,
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.userList = result
            });
    }
    // 获取班组
    getOrganizationUnit() {
        this._productionAssignmentServiceProxy.getOrganizationUnit(
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.getOrganizationUnitList = result
                let idArr = [result[0].id]
                this.getOrganizationUnitUsersById(idArr)
            });
    }
    //班组 change事件
    unitChangeEv(ev) {
        let idArr = []
        ev.forEach(element => {
            idArr.push(element.id)
        });
        this.getOrganizationUnitUsersById(idArr)
    }
    unitChangeEvSingle(ev) {
        let idArr = []
        idArr.push(ev.id);
        this.getOrganizationUnitUsersById(idArr)
    }
    // 单选班组change事件
    unitChangeonlyEv(ev, car) {
        let idArr = [ev.id]
        this.getOrganizationUnitUsersById(idArr, car)
    }
    // 获取装配人员n
    getOrganizationUnitUsersById(organizationIdList, car?) {
        this._productionAssignmentServiceProxy.getOrganizationUnitUsersById(
            organizationIdList
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.getOrganizationUnitUsersByIdList = result
                this.getOrganizationUnitUsersByIdList.forEach(element => {
                    element.val = []
                });
                if (car) {
                    car.getOrganizationUnitUsersByIdList = this.getOrganizationUnitUsersByIdList
                    car.userName = car.getOrganizationUnitUsersByIdList.filter((ele, index) => {
                        return ele.id === car.userId
                    })[0]
                }
            });
    }
    // 查询列表 状态数据
    getProductingStatusDescEv() {
        this._productionReportServiceProxy.getProductingStatusDesc(
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.productingStatus = result
            });
    }

    //重置
    reset() {
        this.queryInfo = {
            time: "",
            assemblyTime: "",
            jobNumber: "",
            techniqueName: "",
            techniqueNumber: "",
            processesName: "",
            workStepName: "",
            startTime: null,
            endTime: null,
            organizationUnitDesc: "",
            userName: "",
            productingStatus: undefined,
            assemblyStartTime: null,
            assemblyEndTime: null,
            inspectionTypeDescId: "",
            organizationUnitId: ""

        }
    }
    //弹窗隐藏
    displayclose(): void {
        this.crewListArr = [];
        this.getOrganizationUnitUsersByIdList = [];
        this.addInfoUi = {
            inspectionTypeDescId: undefined,//一级异常id
            inspectionItemInfoId: undefined,//二级异常id
            inspectionSeverityDescId: undefined,//异常等级id
            handlerId: undefined,//处理人id
            inspectionDetails: "",//异常描述
            codeFormatId: undefined,//编码规则id
            inspectionFileUploadDto: [],
            taskCode: undefined

        };//新增集合
        this.queryInfo = {
            jobNumber: "",
            techniqueName: "",
            techniqueNumber: "",
            processesName: "",
            workStepName: "",
            startTime: null,
            endTime: null,
            time: "",
            assemblyTime: "",
            organizationUnitDesc: "",
            userName: "",
            productingStatus: undefined,
            assemblyStartTime: null,
            assemblyEndTime: null,
            inspectionTypeDescId: "",
            organizationUnitId: ""
        };//查询条件
        this.uploadedFiles = []
    }
    //编码规则 下拉列表
    getFormatDropList(): void {
        this._codeFormatDescServiceProxy.getCodeFormatDropList()
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.formatDropList = result
            });
    }
    // 异常提报 
    addStandardDesc(): void {
        this.myUploader()
        this.savingAddDia = true
        this.addInfo.inspectionTypeDescId = this.addInfoUi.inspectionTypeDescId.id
        this.addInfo.inspectionItemInfoId = this.addInfoUi.inspectionItemInfoId.id
        this.addInfo.inspectionSeverityDescId = this.addInfoUi.inspectionSeverityDescId.id
        this.addInfo.handlerId = this.addInfoUi.handlerId.id
        this.addInfo.inspectionDetails = this.addInfoUi.inspectionDetails
        this.addInfo.userId = this._user.userId
        this.addInfo.taskCode = this.addInfoUi.taskCode.jobNumber
        this.addInfo.taskCodeId = this.addInfoUi.taskCode.id
        this.addInfo.inspectionFileUploadDto = this.addInfoUi.inspectionFileUploadDto
        if (this.addInfoUi.id) {
            this.addInfo.id = this.addInfoUi.id
        } else {
            this.addInfo.id = '00000000-0000-0000-0000-000000000000'
            // this.addInfo.codeFormatId = this.addInfoUi.codeFormatId.id
        }
        if (this.saveFlag) {
            this.saveFlag = false;
            this._inspectionStartServiceProxy.createOrUpdateInspectionStandardDesc(
                this.addInfo
            )
                .pipe(finalize(() => { this.savingAddDia = false }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this.addVisible = false
                        this._messageService.success('添加成功');
                        this.getDescList()
                    } else {
                        this._messageService.error(result.message)
                    }
                });
        }
    }
    // 上传图片
    myUploader() {
        this.addInfoUi.inspectionFileUploadDto = []
        for (const iterator of this.uploadedFiles) {
            if (iterator.lastModified) {
                let file = {
                    fileName: iterator.name,
                    data: iterator
                }
                this._inspectionFileCommonServiceServiceProxy.inspectionUploadFile(file, undefined).pipe(finalize(() => { }))
                    .subscribe(result => {
                        let obj = new InspectionFileUploadDto()
                        obj.fileName = result.fileName,
                            obj.id = result.id,
                            obj.fileUrl = result.fileUrl,
                            this.addInfoUi.inspectionFileUploadDto.push(obj)

                    });
            } else {
                let obj = new InspectionFileUploadDto()
                obj.fileName = iterator.name,
                    obj.id = iterator.id,
                    obj.fileUrl = iterator.objectUrl,
                    this.addInfoUi.inspectionFileUploadDto.push(obj)
            }
        }


    }
    //上传图片删除操作
    myRemove(event) {
        let files = this.addInfoUi.inspectionFileUploadDto.filter((item) => {
            return item.fileName != event.file.name
        })
        this.addInfoUi.inspectionFileUploadDto = files
    }
    //回显删除
    remoteFile(item) {
        let files = this.uploadedFiles.filter((ele) => {
            return ele.name != item.name
        })
        this.uploadedFiles = files
    }
    /**
     * 生产报工
          /// 任务编号 JobNumber
          /// 名称  TechniqueName
          /// 工艺编号  TechniqueNumber
          /// 工序名称 ProcessesName
          /// 工步内容 WorkStepName
          /// 计划开始时间 StartTime
          /// 计划完成时间 EndTime
          /// 装配班组描述 OrganizationUnitDesc
          /// 装配人员描述 UserName
          /// 计划状态 ProductingStatus
          /// 装配开始时间 AssemblyStartTime
          /// 装配结束时间  AssemblyEndTime
     */
    getDescList(event?: LazyLoadEvent): void {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        let productingStatus
        if (this.queryInfo.productingStatus != undefined) {
            productingStatus = this.queryInfo.productingStatus.value
        }
        if (this.queryInfo.time != "") {
            this.queryInfo.startTime = moment(this.queryInfo.time[0])
            this.queryInfo.endTime = moment(this.queryInfo.time[1])
        }
        if (this.queryInfo.assemblyTime != "") {
            this.queryInfo.assemblyStartTime = moment(this.queryInfo.assemblyTime[0])
            this.queryInfo.assemblyEndTime = moment(this.queryInfo.assemblyTime[1])
        }
        let userId: any = this.queryInfo.userName
        let idStr = "", idnameStr = "", unitIdStr = "", unitnameStr = "";
        let organizationUnitId: any = this.queryInfo.organizationUnitDesc

        if (this.queryInfo.userName) {
            userId.forEach(element => {
                idStr += `${element.id},`
                idnameStr += `${element.userName},`

            });
            idStr = idStr.substring(0, idStr.length - 1)
            idnameStr = idnameStr.substring(0, idnameStr.length - 1)
        }
        if (this.queryInfo.organizationUnitDesc) {
            organizationUnitId.forEach(element => {
                unitIdStr += `${element.id},`
                unitnameStr += `${element.displayName},`

            });
            unitIdStr = unitIdStr.substring(0, unitIdStr.length - 1)
            unitnameStr = unitnameStr.substring(0, unitnameStr.length - 1)
        }
        this._productionReportServiceProxy.getTaskReport(
            this.queryInfo.jobNumber,
            this.queryInfo.techniqueName,
            this.queryInfo.techniqueNumber,
            this.queryInfo.processesName,
            this.queryInfo.workStepName,
            this.queryInfo.startTime,
            this.queryInfo.endTime,
            unitnameStr,
            idnameStr,
            productingStatus,
            this.queryInfo.assemblyStartTime,
            this.queryInfo.assemblyEndTime,
            this.primengTableHelper.getSorting(this.dataTable),//undefined
            this.primengTableHelper.getMaxResultCount(this.paginator, event),//10
            this.primengTableHelper.getSkipCount(this.paginator, event)//0
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();

            });
    }
    //开始报工
    startReport(id) {
        this._messageService.confirm(
            '确定开始报工？',
            (isConfirmed) => {
                if (isConfirmed) {
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        this._productionReportServiceProxy.startTaskReport(
                            id
                        )
                            .pipe(finalize(() => { }))
                            .subscribe(result => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this.getDescList()
                                } else {
                                    this._messageService.error(result.message)
                                }
                            });
                    }
                }
            }
        );

    }
    //履历
    llVisibleEv(id) {
        this.llVisible = true
        this._operationHistoryServiceProxy.getOperationLogList(
            id
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.logList = result

            });

    }

}